class Admin::Targets::StudentsController < ApplicationController
  layout 'admin'
  def index 
    @students = Student.where(company_id: current_company.id, service_employee_id: nil).uniq
  end

  def show
    @student = Student.find_by(id: params[:id], company_id: current_company.id)
    if @student.present?
      respond_to do |format|
        format.html
      end		
    else
      redirect_to admin_targets_students_path
    end
  end

  def assign
    @student = Student.find_by(id: params[:id], company_id: current_company.id)
    user_employee = current_user.employees.find_by(company_id: current_company.id)
    studio_ids = user_employee.employee_of_studios.map {|es| es.studio_id if es.position_configuration.position_name == "运营总监"}
    studio_ids = studio_ids.uniq.compact
    conditions = ["1=1"]
    conditions << "studios.id in (#{studio_ids.join(",")})" if studio_ids.present?
    conditions << "position_configurations.position_name = '服务顾问'"
    @employees = Employee.joins(:employee_of_studios => [:studio, :position_configuration]).where(conditions.join(" and ")).distinct
  end

  def update
    @student = Student.find(params[:id])
    @student.update!(student_params)
    respond_to do |format|
      format.js { render :js => "window.location.href = '/admin/targets/students'" }
    end
  end


  private

  def student_params
    params.require(:student).permit(:service_employee_id)
  end
end
